<?php

namespace app\admin\model;
use think\Model;
use think\Db;

class NoteModel extends Model
{
    protected $name = 'note';
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    public function getByCount($map)
	{
		return Db::name('note')->where($map)->count();
	}

    /**
     * 根据搜索条件获取用户列表信息
     * @author 【朱沪宁】
     */
    public function getNoteByWhere($map, $Nowpage, $limits)
    {
        return $this->field('think_note.*,b.nickname as name,c.nickname as to_name')
            ->join('think_member b', 'think_note.user_id = b.id')
            ->join('think_member c', 'think_note.to_user_id = c.id')
            ->where($map)->page($Nowpage, $limits)->order('think_note.create_time desc')->select();
    }

    
    /**
     * [insertNote 添加信息]
     * @author 【朱沪宁】
     */
    public function insertNote($param)
    {
        try{
            $result = $this->allowField(true)->save($param);
            if(false === $result){             
                return ['code' => -1, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '添加成功'];
            }
        }catch( PDOException $e){
            return ['code' => -2, 'data' => '', 'msg' => $e->getMessage()];
        }
    }



    /**
     * [updateNote 编辑信息]
     * @author 【朱沪宁】
     */
    public function updateNote($param)
    {
        try{
            $result = $this->allowField(true)->save($param, ['id' => $param['id']]);
            if(false === $result){          
                return ['code' => 0, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '编辑成功'];
            }
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }



    /**
     * [getOneNote 根据信息id获取一条信息]
     * @author 【朱沪宁】
     */
    public function getOneNote($id)
    {
        return $this->where('id', $id)->find();
    }



    /**
     * [delNote 删除信息]
     * @author 【朱沪宁】
     */
    public function delNote($id)
    {
        try{
            $this->where('id', $id)->delete();
            return ['code' => 1, 'data' => '', 'msg' => '删除成功'];
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }

    /**
     * 根据用户UID  获取用户 资料列表
     *
     */
    public function memberNote($uid){

        return $this->alias('a')->join('think_note_member m','a.id = m.note_id')->where('m.member_id',$uid)->order('m.createtime desc')->select();
    }

    public function getAllNote()
    {
        return $this->field('think_note.*')->order('id asc')->select();
    }

}